package com.etl.jdbc.jdbc;


import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * 分页相关工具类
 *
 * User: Locker1995
 * Date: 2018-03-28
 * Time: 10:42 AM
 */
public class PageUtil {

    public static JSONObject getPageObject(long count, List<JSONObject> data, int pageSize, int pageNumber){

        long pageCount = count/pageSize;

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("pageCount",pageCount);

        jsonObject.put("data",data);

        jsonObject.put("pageSize",pageSize);

        jsonObject.put("pageNumber",pageNumber);

        jsonObject.put("count",count);

        return jsonObject;
    }

    /**
     *
     * 获得分页语句
     *
     * @param database
     * @param tableName
     * @param pageSize
     * @param pageNumber
     * @return
     */
    public static String getPageSql(String database,String tableName,int pageSize,int pageNumber){

        String sql="";

        if("mysql".equals(database.toLowerCase())){
            sql="select * from "+tableName+" limit "+((pageNumber-1)<0?0:(pageNumber-1))*pageSize+" , "+pageSize+" ";
        }

        if("sqlserver".equals(database.toLowerCase())){

            sql="select * FROM (" +
                    "SELECT ROW_NUMBER() OVER (ORDER BY (select 0)) as rn,* FROM "+tableName +
                    ") " +
                    "as a where a.rn BETWEEN "+pageNumber*pageSize+" and "+((pageNumber+1)*pageSize-1);

        }

        if("oracle".equals(database.toLowerCase())){

            sql="select * FROM " +
                    "(" +
                    "select ROWNUM AS rn ,a.* FROM (" +
                    "select * from "+tableName +
                    ") a " +
                    ") " +
                    "where rn BETWEEN "+pageNumber*pageSize+" and "+(pageNumber+1)*pageSize;

        }

        return sql;
    }

    /**
     *
     * 获得统计语句
     *
     * @param database
     * @param tableName
     * @return
     */
    public static String getCountSql(String database,String tableName){

        String sql="";

        if("mysql".equals(database.toLowerCase()))
            sql = "select count(*) as count  from "+tableName+" ";

        if("sqlserver".equals(database.toLowerCase()))
            sql="select count(*) as count from "+tableName;

        if("oracle".equals(database.toLowerCase()))
            sql="select count(*) as count from "+tableName;


        return sql;
    }

}
